//
//  SydOTA.m
//  GetFit3.0
//
//  Created by 圆圆陈 on 2018/1/17.
//  Copyright © 2018年 lxc. All rights reserved.
//

#import "SydOTA.h"
@interface SydOTA (){
    UInt32 _checkSum, _size, _sendSize;
    UInt8  m_Current_Command;
}

@property (nonatomic, assign) int sendCount;
@property (nonatomic, assign) int totalCount;
@end

@implementation SydOTA

- (void)OTA_START:(NSString *)identifire data:(id)data {
    NSData *binData;
    
    if (data && [data isKindOfClass:[NSString class]]) {
        binData = [NSData dataWithContentsOfURL:[NSURL URLWithString:data]];
    } else if (data && [data isKindOfClass:[NSData class]]) {
        binData = data;
    }
    if (!binData) {
        NSLog(@"固件包错误");
        return;
    }
    _sendSize  = 0;
    _sendCount = 0;
    int size = binData.length / 15;
    int more = binData.length % 15;
    _totalCount = size;
    if (more > 0) {
        _totalCount++;
    }
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self OTA_Erase_Flash:identifire];
        [self OTA_Write_Flash:identifire data:binData];
        [self OTA_Upgrade_Flash:_size checkNum:_checkSum identifire:identifire];
    });
}

- (void)OTA_Erase_Flash:(NSString *)identifire {
    usleep(50000);
    UInt8  val[2] = {0x16, 0x00};
    NSData *sData = [[NSData alloc] initWithBytes:val length:2];
    m_Current_Command = 0x16;
    [self OTA_Write:identifire data:sData];
}

- (void)OTA_Write_Flash:(NSString *)identifire data:(NSData *)binData {
    m_Current_Command = 0x17;
    _size             = (UInt32)binData.length;
    unsigned char *bytes = (unsigned char *)[binData bytes];
    _checkSum = 0;
    for (int i = 0; i < binData.length; i++) {
        _checkSum += (UInt32)bytes[i];
        _checkSum &= 0x0000FFFF;
    }
    NSInteger totalLength   = binData.length;
    NSInteger subDataOffset = 0;
    int       count         = 0;
    while (1) {
        NSInteger remainLength = totalLength - subDataOffset;
        if (remainLength >= 15) {
            NSData *sub = [self appendData:[binData subdataWithRange:NSMakeRange(subDataOffset, 15)] address:subDataOffset];
            [self OTA_Write:identifire data:sub count:count];
        } else {
            NSData *sub = [binData subdataWithRange:NSMakeRange(subDataOffset, remainLength)];
            NSLog(@"OTA第二步完成");
            sub = [self appendData:sub address:subDataOffset];
            [self OTA_Write:identifire data:sub count:count];
            break;
        }
        subDataOffset += 15;
    }
}

- (void)OTA_Upgrade_Flash:(UInt16)size checkNum:(UInt16)checkNum identifire:(NSString *)identifire {
    usleep(50000);
    NSLog(@"ota第三步");
    UInt8 val[6] = {0};
    val[0] = 0x18;
    val[1] = 0x04;
    val[2] = (UInt8)(_size & 0x00FF);
    val[3] = (UInt8)((_size & 0xFF00)>>8);
    val[4] = (UInt8)(_checkSum & 0x00FF);
    val[5] = (UInt8)((_checkSum & 0xFF00)>>8);
    NSData *sData = [[NSData alloc] initWithBytes:val length:6];
    m_Current_Command = 0x18;
    [KK_BLEService senderDataToPeripheral64:sData];
    dispatch_async(dispatch_get_main_queue(), ^{
        if (_sydotaProgressBlock) {
            _sydotaProgressBlock(100);
        }
    });
}

- (void)OTA_Write:(NSString *)identifire data:(NSData *)data {
    NSLog(@"OTA DATA : %@", data);
    [KK_BLEService senderDataToPeripheral64:data];
    //    [self.bleClient writeCharacteristic:identifire suuid:kServiceUUIDFirmwareUpdate cuuid:kCharacteristicsUUIDFirmwareUpdateReadWrite data:data type:0 complete:^(BOOL success) {
    //        [self.bleClient readCharacteristic:identifire suuid:kServiceUUIDFirmwareUpdate cuuid:kCharacteristicsUUIDFirmwareUpdateReadWrite];
    //    }];
}

- (void)OTA_Write:(NSString *)identifire data:(NSData *)data count:(int)count {
    _sendCount++;
    [KK_BLEService senderDataToPeripheral64:data];
    usleep(80000);
    _sendSize += 15;//因为_size是拼包头前的长度,所以这个也是
    int progress = (int)(1.0 *_sendCount/_totalCount *100);
    dispatch_async(dispatch_get_main_queue(), ^{
        if (_sydotaProgressBlock) {
            _sydotaProgressBlock(progress);
        }
    });
//    NSLog(@"总%d包 第几包数据>>>>>%d 进度>>>>%d", _totalCount, _sendCount, progress);
}

- (NSData *)appendData:(NSData *)subData address:(UInt16)address {
    UInt8 val[5] = {0};
    
    val[0] = 0x17;
    val[1] = 0x13;
    val[2] = (UInt8)(address & 0x00FF);
    val[3] = (UInt8)((address & 0xFF00)>>8);
    val[4] = subData.length;
    NSData        *sData = [[NSData alloc] initWithBytes:val length:5];
    NSMutableData *data  = [[NSMutableData alloc]init];
    [data appendData:sData];
    [data appendData:subData];
    return data;
}

@end

